<?php
/**
 * (c) 2010 Philip Clarke, Bouncing Limited.
**/


if( ( defined('MODULE_AUTO_UPDATE_LOCATION') && file_exists(dirname(DIR_FS_CATALOG.'/').'/'.MODULE_AUTO_UPDATE_LOCATION.'/update.php') || (!file_exists(DIR_FS_CATALOG.'/page_not_found.html') ) ) && !isset($_GET['cache']) ){

  if( ( (time()-(int)MODULE_AUTO_UPDATE_TIME)>24*60*60) ){

  $sql = "UPDATE `".TABLE_CONFIGURATION."` SET configuration_value=".time()." WHERE configuration_key='MODULE_AUTO_UPDATE_TIME'";

  $db->Execute($sql);

  $url = HTTP_SERVER.MODULE_AUTO_UPDATE_LOCATION.'update.php' ;

  $a = parse_url($url);

  $fp = fsockopen( ( isset($_SERVER['HTTPS']) ? 'ssl://'.$a['host'] : $a['host']), (isset($_SERVER['HTTPS']) ? 443 : 80 ), $errno, $errstr, 5);
  if ($fp) {
    $out = "HEAD ".DIR_WS_CATALOG.MODULE_AUTO_UPDATE_LOCATION."update.php HTTP/1.1\r\n";
    $out .= "Host: ".$a['host']."\r\n";
    $out .= "Accept: */*\r\n";
    $out .= "Content-length: 0\r\n\r\n";
    fwrite($fp, $out);
    fclose($fp);
  }


  unset ($a, $status, $url, $sql);

  } // end of 24 hour delay


}

if(!defined('MODULE_CACHE_404_GEN')){

  $sql = "INSERT INTO `".TABLE_CONFIGURATION."` (configuration_value, configuration_key, configuration_group_id, date_added, last_modified) VALUES (".time().", 'MODULE_CACHE_404_GEN', 6, NOW(), NOW())";

  print $sql;

  $db->Execute($sql);

  define('MODULE_CACHE_404_GEN', (time()-3*60*60) );

}


// generates a static 404 page
if(!isset($_GET['cache']) && ( !file_exists(DIR_FS_CATALOG.'/page_not_found.html') || ( (time()-(int)MODULE_CACHE_404_GEN)>2*60*60)  ) ){

  $sql = "UPDATE `".TABLE_CONFIGURATION."` SET configuration_value=".time().", last_modified=NOW() WHERE configuration_key='MODULE_CACHE_404_GEN'";

  $db->Execute($sql);

  $url = HTTP_SERVER.DIR_WS_CATALOG.'index.php?main_page=page_not_found&cache=true' ;


  $a = parse_url($url);


  $pnf = new httpClient;

  $pnf->addHeader('Host', $a['host']);
  $pnf->protocolVersion = '1.0';

  $status = $pnf->get($url);

  $str = $pnf->responseBody ;

  // print $str ;

  $fc->unlock(DIR_FS_CATALOG);
  $fc->unlock(DIR_FS_CATALOG.'/page_not_found.html');
  $fp = fopen(DIR_FS_CATALOG.'/page_not_found.html', 'w+');

  fwrite($fp, $str);

  fclose($fp);

  $fc->relock(DIR_FS_CATALOG.'/page_not_found.html');
  $fc->relock(DIR_FS_CATALOG);

  unset($pnf, $a );

}


